package cn.northsea.utils;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import java.util.Map;

public class AliyunSmsUtils {
    private static final String REGION_ID = "cn-hangzhou";
    private static final String DOMAIN = "dysmsapi.aliyuncs.com";
    private static final String VERSION = "2017-05-25";
    private static final String ACTION= "SendSms";
    private static final String accessKeyId = "LTAI5tQypYRLwUKGVc23MrHx";
    private static final String secret = "xTMdOFT8vz2PwEVbExwdce6CzWcaP1";

    /**
     * 功能描述：阿里云短信服务-发送短信（验证码，通知类短信）
     *
     * PhoneNumbers允许传递多个，中间以逗号分隔 15551725506，15551725506
     * SignName ：签名必填
     * TemplateCode：模板code必填
     * TemplateParam：模板参数 不必填
     * @return true发送成功 false发送失败
     */
    public static Boolean sendSms(Map<String,String> map) {
        boolean flag = false;
        if(map == null) {
            return flag;
        }
        //校验手机号格式是否正确 "{\"code\":\"2111\"}"
        DefaultProfile profile = DefaultProfile.getProfile(REGION_ID,
                accessKeyId, secret);
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);//设置post提交
        request.setDomain(DOMAIN);//短信API产品域名（接口地址固定，无需修改）
        request.setVersion(VERSION);
        request.setAction(ACTION);
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", map.get("phoneNumbers"));
        request.putQueryParameter("SignName", map.get("signName"));//短信签名
        request.putQueryParameter("TemplateCode", map.get("templateCode"));
        request.putQueryParameter("TemplateParam", map.get("templateParam"));
        try {
            CommonResponse response = client.getCommonResponse(request);
            Map<String,String> responseMap = JSON.parseObject(response.getData(), Map.class);
            if(responseMap.get("Code").equals("OK")) {
                flag = true;
            }
            System.out.println(response.getData());
        }
        catch (ServerException e) {
            throw new RuntimeException(e);
        }
        catch (ClientException e) {
            throw new RuntimeException(e);
        }
        return flag;
    }
}
